<template>
  <div>
    <Bread1 :breadtitle="breadtitle"></Bread1>
    <a-alert message="只能选择三级菜单" banner />
    <!-- 树选择器 -->
    <a-tree-select
      class="tree"
      :replaceFields="{
        title: 'cat_name',
        children: 'children',
        value: 'cat_id',
        key: 'cat_id',
      }"
      v-model="selectkey"
      @change="handleChange"
      style="width: 15%"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      :tree-data="catelist"
      placeholder="请选择三级菜单！"
    >
    </a-tree-select>

    <!-- tag -->
    <a-tabs :default-active-key="activeName" @change="handTabClick">
      <a-tab-pane key="many" tab="动态参数">
        <!-- 添加动态参数按钮 -->
        <a-button type="primary" :disabled="isBtnDisabled" @click="showModal">
          添加参数
        </a-button>
        <!-- 动态参数表格 -->
        <a-table :columns="columns" :data-source="manyTabData" rowKey="attr_id">
          <span slot="action" slot-scope="text, record" href="javascript:;">
            <a-space>
              <a-button type="primary" @click="alterModal(record.attr_id)">
                修改
              </a-button>
              <a-popconfirm
                title="是否删除?"
                ok-text="Yes"
                cancel-text="No"
                @confirm="confirm(record)"
              >
                <a-button type="danger"> 删除 </a-button>
              </a-popconfirm>
            </a-space>
          </span>
          <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
            <!-- 循环渲染tag -->
            <a-tag
              closable
              v-for="(item, index) in record.attr_vals"
              :key="index"
              color="orange"
              @close="handleClose(index, record)"
            >
              {{ item }}
            </a-tag>
            <!-- 输入tag -->
            <a-input
              v-if="record.inputVisible"
              ref="input"
              type="text"
              size="small"
              :style="{ width: '78px' }"
              v-model="record.inputValue"
              @blur="handleInputConfirm(record)"
              @keyup.enter="handleInputConfirm(record)"
            />
            <a-tag
              v-else
              style="background: #fff; borderstyle: dashed"
              @click="showInput(record)"
            >
              <a-icon type="plus" /> New Tag
            </a-tag>
          </p>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="only" tab="静态属性" force-render>
        <!-- 添加动态参数按钮 -->
        <!-- 静态参数表格 -->
        <a-button type="primary" :disabled="isBtnDisabled" @click="showModal">
          添加属性
        </a-button>
        <a-table :columns="columns" :data-source="onlyTabData" rowKey="attr_id">
          <span slot="action" slot-scope="text, record" href="javascript:;">
            <a-space>
              <a-button type="primary" @click="alterModal(record.attr_id)">
                修改
              </a-button>
              <a-popconfirm
                title="是否删除?"
                ok-text="Yes"
                cancel-text="No"
                @confirm="confirm(record)"
              >
                <a-button type="danger"> 删除 </a-button>
              </a-popconfirm>
            </a-space>
          </span>
          <p slot="expandedRowRender" slot-scope="record" style="margin: 0">
            <!-- 循环渲染tag -->
            <a-tag
              closable
              v-for="(item, index) in record.attr_vals"
              :key="index"
              color="orange"
              @close="handleClose(index, record)"
            >
              {{ item }}
            </a-tag>
            <!-- 输入tag -->
            <a-input
              v-if="record.inputVisible"
              ref="input"
              type="text"
              size="small"
              :style="{ width: '78px' }"
              v-model="record.inputValue"
              @blur="handleInputConfirm(record)"
              @keyup.enter="handleInputConfirm(record)"
            />
            <a-tag
              v-else
              style="background: #fff; borderstyle: dashed"
              @click="showInput(record)"
            >
              <a-icon type="plus" /> New Tag
            </a-tag>
          </p>
        </a-table>
      </a-tab-pane>
    </a-tabs>

    <!-- 添加参数对话框 -->
    <a-modal
      v-model="visible"
      :title="'添加' + titleText"
      @cancel="$refs.ruleForm.resetFields()"
      @ok="handleOk"
    >
      <a-form-model
        ref="ruleForm"
        :model="addForm"
        :rules="addFormRules"
        v-bind="layout"
      >
        <a-form-model-item has-feedback :label="titleText" prop="attr_name">
          <a-input v-model="addForm.attr_name" autocomplete="off" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 修改参数对话框 -->
    <a-modal
      v-model="altervisible"
      :title="'修改' + titleText"
      @cancel="$refs.ruleForm.resetFields()"
      @ok="alterOk"
    >
      <a-form-model
        ref="ruleForm"
        :model="addForm"
        :rules="addFormRules"
        v-bind="layout"
      >
        <a-form-model-item has-feedback :label="titleText" prop="attr_name">
          <a-input v-model="addForm.attr_name" autocomplete="off" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: "序号",
    customRender: (text, record, index) => `${index + 1}`,
    align: "center",
  },
  { title: "参数名称", dataIndex: "attr_name", key: "attr_name" },
  {
    title: "操作",
    dataIndex: "",
    key: "x",
    scopedSlots: { customRender: "action" },
  },
];
import Bread1 from "@/components/bread/Bread1";
import {
  reqCateList,
  reqDyOrSt,
  reqsuDyOrSt,
  reqalterDyOrSt,
  reqdelAtt,
  reqAddTag,
} from "@/api";
export default {
  data() {
    return {
      breadtitle: ["商品管理", "参数列表"],
      // 树选择器数据
      catelist: [],
      // 被选中的三级菜单id
      selectkey: "",
      // tab的key
      activeName: "many",
      // 动态参数数据
      manyTabData: [],
      //静态参数数据
      onlyTabData: [],
      columns,
      // 对话框属性
      visible: false,
      altervisible: false,
      // 添加参数表单
      addForm: {
        attr_name: "",
      },
      // 添加表单顺序
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      // 所修改的id
      currentIndexId: "",
      // 添加扁担验证对象
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: "请输入参数名称",
            trigger: "blur",
          },
          {
            min: 1,
            max: 15,
            message: "请输入1-15位数字，汉字或者英文",
            trigger: "blur",
          },
        ],
      },
      // // 添加tag
      // inputVisible: false,
      // // tag内容
      // inputValue: "",
    };
  },
  components: { Bread1 },
  created() {
    // 获取商品分类
    this.getCateList();
  },
  computed: {
    // 计算按钮禁用
    isBtnDisabled() {
      if (this.selectkey != "") {
        return false;
      } else {
        return true;
      }
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
  methods: {
    // 三级菜单网络请求
    async getCateList() {
      let res = await reqCateList();
      // console.log(res.data);
      if (res.meta.status == 200) {
        this.catelist = res.data;
      }
    },
    // 三级菜单选择
    handleChange(value, label, extra) {
      if (extra.triggerNode.$children.length > 0) {
        this.selectkey = "";
        this.manyTabData = [];
        this.onlyTabData = [];
        this.$message.warning("请选择三级菜单！");
        return;
      }
      // console.log(this.selectkey,this.activeName);
      // this.getParamsData(this.selectkey,this.activeName)
      this.getParamsData(this.selectkey, this.activeName);
    },
    // tab切换
    handTabClick(activeKey) {
      // 根据面板id获取数据
      this.getParamsData(this.selectkey, activeKey);
      this.activeName = activeKey;
    },
    async getParamsData(id, name) {
      // 根据面板id获取数据
      let res = await reqDyOrSt(id, name);
      if (res.meta.status !== 200) {
        this.$message.warning("获取参数列表失败！");
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制文本框显示隐藏
        item.inputVisible = false;
        item.inputValue = "";
      });
      // console.log(res.data);
      if (name === "many") {
        this.manyTabData = res.data;
      } else {
        this.onlyTabData = res.data;
      }
    },
    // 添加对话框挂显示
    showModal() {
      this.visible = true;
    },
    // 添加对话框挂关闭确认
    handleOk(e) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        // console.log(this.selectkey, this.addForm.attr_name, this.activeName);
        let res = await reqsuDyOrSt(
          this.selectkey,
          this.addForm.attr_name,
          this.activeName
        );
        if (res.meta.status !== 201) {
          this.$message.warning("添加失败！");
        }
        this.$message.success("添加成功!");
        this.visible = false;
        this.$refs.ruleForm.resetFields();
        this.getParamsData(this.selectkey, this.activeName);
      });
    },
    // 修改对话框确认关闭
    alterOk() {
      this.$refs.ruleForm.validate(async (vaild) => {
        if (!vaild) return;
        // console.log(
        //   this.selectkey,
        //   this.currentIndexId,
        //   this.activeName,
        //   this.addForm.attr_name
        // );
        let res = await reqalterDyOrSt(
          this.selectkey,
          this.currentIndexId,
          this.activeName,
          this.addForm.attr_name
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败！");
        }
        this.$message.success("修改成功！");
        this.getParamsData(this.selectkey, this.activeName);
        this.altervisible = false;
        this.$refs.ruleForm.resetFields();
      });
      this.altervisible = false;
    },
    // 修改对话框打开
    alterModal(id) {
      this.currentIndexId = id;
      this.altervisible = true;
    },
    // 删除
    async confirm(record) {
      const { attr_id } = record;
      let res = await reqdelAtt(this.selectkey, attr_id);
      if (res.meta.status !== 200) {
        this.$message.error("删除失败！");
      }
      this.$message.success("删除成功！");
      this.getParamsData(this.selectkey, this.activeName);
    },
    // 文本框失去焦点
    async handleInputConfirm(record) {
      console.log(record.inputValue);
      if (record.inputValue.trim().length === 0) {
        record.inputValue = "";
        record.inputVisible = false;
        return;
      }

      record.attr_vals.push(record.inputValue.trim());
      record.inputValue = "";
      record.inputVisible = false;
      console.log(record.attr_sel);
      const data = {
        attr_name: record.attr_name,
        attr_sel: record.attr_sel,
        attr_vals: record.attr_vals.join(" "),
      };
      let res = await reqAddTag(this.selectkey, record.attr_id, data);
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("添加失败！");
      }
      this.$message.success("添加成功！");
    },
    // 点击按钮
    showInput(record) {
      record.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },
    async handleClose(index, record) {
      record.attr_vals.splice(index, 1);
      console.log(record.attr_vals);
      const data = {
        attr_name: record.attr_name,
        attr_sel: record.attr_sel,
        attr_vals: record.attr_vals.join(" "),
      };
      let res = await reqAddTag(this.selectkey, record.attr_id, data);
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("删除失败！");
      }
      this.$message.success("删除成功！");
    },
  },
};
</script>

<style lang="less" scoped>
.tree {
  margin-top: 15px;
}
</style>